<template></template>

<script setup lang="ts">
import * as L from 'leaflet'
import type { IPixelLayerStyle3DOptions } from '@quickearth/core'
import {
  GridDataGLFillMode,
  QEGridDataProvider,
  getBinary,
  resourceService
} from '@quickearth/core'
const centerApi = import.meta.env.VITE_BASE_URL
import { LPixelLayer } from '@quickearth/leaflet'
import { fireInsuranceStore } from '@/pages/forestry/store/store'
import apiList from '@/pages/forestry/api/api'
const fireStore = fireInsuranceStore()
const gdskjcCurrentActive = computed(() => fireStore.gdskjcCurrentActive)
const timerIndex = computed(() => fireStore.timerIndex)
const rowData = ref([])
const baseMap = inject('baseMap')
const layers = L.layerGroup().addTo(toRaw(baseMap.value))
async function updateGridLayer() {
  layers.clearLayers()
  await resourceService.loadResourceFromConfigPath(
    'demos/styles/demo.config.json'
  )
  const Buffer = await getBinary(
    centerApi + rowData.value[timerIndex.value].fileUrl
  )
  const provider = new QEGridDataProvider(Buffer[0])
  const layer = new LPixelLayer()
  const style: IPixelLayerStyle3DOptions = {
    fillColor: `color-slhx#res`,
    fillMode: GridDataGLFillMode.pixel1,
    zScale: 0,
    globalOpacity: 1,
    opaque: true,
    extrudeScale: 1
  }
  layer.setDataSource(provider).setDrawOptions(style)
  layers.addLayer(layer)
  fireStore.mapLoading = false
}

// useEventBus('handleShowGridPointMonitoringLayer').on(handleShowLayer)
const initData = () => {
  apiList.getGridPointForestFireDangerLevel().then(res => {
    if (res.data) {
      rowData.value = res.data
      fireStore.gdskjcAllDataList = res.data
      updateGridLayer()
    }
  })
}
watch(
  () => timerIndex.value,
  newV => {
    updateGridLayer()
  }
)
watch(
  () => gdskjcCurrentActive.value,
  val => {
    if (val !== 'none') {
      if (layers) {
        layers.clearLayers()
      }
      initData()
    } else {
      layers.clearLayers()
    }
  },
  {
    deep: true
  }
)
onMounted(() => {
  if (gdskjcCurrentActive.value !== 'none') {
    initData()
  }
})
onUnmounted(() => {
  layers.clearLayers()
})
</script>

<style scoped lang="scss"></style>
